<template>
  <view class="page">
    <uni-nav-bar
      :title="` `"
      color="#333"
      left-icon="left"
      showMenuButtonWidth
      statusBar
      fixed
      backgroundColor="transparent"
      :border="false"
      @clickLeft="$tools.back"
    />
    <image
      :src="product.productImg"
      class="product-img"
    />
    <!-- 产品标题 -->
    <view class="product-title">
      <view class="product-name">{{ product.productName }}</view>
      <view class="product-fav">
        <image src="/static/images/menu/unfavorited.png" />
        <view>收藏口味</view>
      </view>
    </view>
    <view class="product-actions">
      <!-- 产品属性 -->
      <view
        class="attrs"
        v-if="hasAttrs"
      >
        <view
          class="attr"
          v-for="(attr, index) in product.productAttrs"
          :key="index"
        >
          <view class="attr-name">{{ attr.attributeName }}</view>
          <view class="attr-values">
            <view
              class="attr-value"
              v-for="(item, attrIndex) in attr.productAttrs"
              :key="item.attributeId"
              :class="{
                selected: selectedAttrIds.includes(item.attributeId)
              }"
              @tap="selectAttr(index, attrIndex)"
            >
              {{ item.attributeName }}
            </view>
          </view>
        </view>
      </view>
      <!-- 产品规格 -->
      <view
        class="specs"
        v-if="hasSpecs"
      >
        <view
          class="spec"
          v-for="(spec, index) in product.productSpecs"
          :key="index"
        >
          <view class="spec-name">{{ spec.specName }}</view>
          <view class="spec-values">
            <view
              class="spec-value"
              :class="[specValueStyle(item)]"
              v-for="item in spec.specs"
              :key="item.specId"
            >
              <view>
                <text>{{ item.specName }}</text>
                <text>¥{{ $tools.formatPrice(item.specPrice) }}</text>
              </view>
              <view class="spec-actions">
                <view class="spec-action">
                  <image
                    src="/static/images/menu/minus.png"
                    v-if="selectedSpecs[item.specId]"
                    @tap="minusSpec(item)"
                  />
                  <view
                    class="spec-count"
                    v-if="selectedSpecs[item.specId]"
                  >
                    {{ selectedSpecs[item.specId] }}
                  </view>
                  <image
                    src="/static/images/menu/plus.png"
                    @tap="addSpec(item)"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="detail">
      <view class="detail-title">商品详情</view>
      <view
        class="detail-desc"
        v-html="product.productDesc"
      />
    </view>
    <view class="bottom">
      <view class="bottom-content">
        <view class="bottom-left">
          <view class="bottom-price"> ¥{{ productPrice }} </view>
          <view class="bottom-attrs">
            {{ attrAndSpecText }}
          </view>
        </view>
        <view class="bottom-right">
          <uni-icons
            type="minus"
            size="26"
            :color="quantity > 1 ? '#E60012' : '#cccccc'"
            @tap="minusQuantity"
          />
          <view class="bottom-quantity">{{ quantity }}</view>
          <image
            src="/static/images/menu/plus.png"
            @tap="addQuantity"
          />
        </view>
      </view>
      <view class="bottom-actions">
        <view class="bottom-btn buy"> 立即购买 </view>
        <view
          class="bottom-btn add"
          @tap="handleAddToCart"
        >
          加入购物车
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import { mapState, mapActions } from "vuex"
export default {
  name: "ProductDetail",
  data() {
    return {
      categoryId: null,
      productId: null,
      selectedAttrIds: [],
      selectedSpecs: {},
      quantity: 1
    }
  },
  onLoad(options) {
    const { categoryId, productId } = options
    this.categoryId = categoryId
    this.productId = productId
    if (this.product.productAttrs.length > 0) {
      this.selectedAttrIds = this.product.productAttrs.map(
        item => item.productAttrs[0].attributeId
      )
    }
  },
  computed: {
    ...mapState("menu", ["menus", "cart"]),
    hasAttrs() {
      return this.product.productAttrs && this.product.productAttrs.length > 0
    },
    hasSpecs() {
      return this.product.productSpecs && this.product.productSpecs.length > 0
    },
    product() {
      const category = this.menus.find(
        item => item.productCategoryId == this.categoryId
      )
      if (category) {
        return category.products.find(item => item.productId == this.productId)
      }
      return {}
    },
    specValueStyle() {
      return item => ({
        selected: this.selectedSpecs[item.specId]
      })
    },
    attrAndSpecText() {
      if (!this.product) return ""
      const attrText =
        this.product.productAttrs && this.product.productAttrs.length > 0
          ? this.product.productAttrs
              .map(item => {
                return item.productAttrs && item.productAttrs.length > 0
                  ? item.productAttrs
                      .map(attr => {
                        if (this.selectedAttrIds.includes(attr.attributeId)) {
                          return attr.attributeName
                        } else {
                          return ""
                        }
                      })
                      .filter(text => text !== "")
                      .join("/")
                  : ""
              })
              .filter(text => text !== "")
              .join("/")
          : ""

      const specText =
        this.product.productSpecs && this.product.productSpecs.length > 0
          ? this.product.productSpecs
              .map(item => {
                return item.specs && item.specs.length > 0
                  ? item.specs
                      .map(spec => {
                        if (this.selectedSpecs[spec.specId]) {
                          return (
                            spec.specName +
                            (this.selectedSpecs[spec.specId] > 1
                              ? "*" + this.selectedSpecs[spec.specId]
                              : "")
                          )
                        } else {
                          return ""
                        }
                      })
                      .filter(text => text !== "")
                      .join("/")
                  : ""
              })
              .filter(text => text !== "")
              .join("/")
          : ""

      return [attrText, specText].filter(text => text !== "").join("/")
    },
    productPrice() {
      let price = this.product.productPrice
      for (const specId of Object.keys(this.selectedSpecs)) {
        for (const specGroup of this.product.productSpecs || []) {
          const foundSpec = specGroup.specs?.find(item => item.specId == specId)
          if (foundSpec) {
            price += foundSpec.specPrice * this.selectedSpecs[specId]
            break
          }
        }
      }
      return this.$tools.formatPrice(price * this.quantity)
    }
  },
  methods: {
    ...mapActions("menu", ["addToCart"]),
    selectAttr(index, attrIndex) {
      this.$set(
        this.selectedAttrIds,
        index,
        this.product.productAttrs[index].productAttrs[attrIndex].attributeId
      )
    },
    addSpec(item) {
      if (this.selectedSpecs[item.specId]) {
        this.selectedSpecs[item.specId]++
      } else {
        this.$set(this.selectedSpecs, item.specId, 1)
      }
    },
    minusSpec(item) {
      if (this.selectedSpecs[item.specId] > 0) {
        this.selectedSpecs[item.specId]--
      }
      if (this.selectedSpecs[item.specId] == 0) {
        delete this.selectedSpecs[item.specId]
      }
    },
    addQuantity() {
      this.quantity++
    },
    minusQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    handleAddToCart() {
      this.addToCart({
        ...this.product,
        selectedAttrIds: this.selectedAttrIds,
        selectedSpecs: this.selectedSpecs,
        productPrice: this.productPrice,
        attrAndSpecText: this.attrAndSpecText,
        quantity: this.quantity
      })
      uni.navigateBack()
    }
  }
}
</script>
<style lang="scss" scoped>
.page {
  position: relative;
}

.product-img {
  width: 750rpx;
  height: 564rpx;
}

.product-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: $uni-spacing-row-base $uni-spacing-row-xl;
  background-color: #fff;
  border-bottom: 1rpx solid $uni-border-color;
}

.product-name {
  font-size: $uni-font-size-xl;
  font-weight: bold;
  color: $uni-text-color;
}

.product-fav {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: $uni-font-size-sm;
  color: $uni-text-color-secondary;

  image {
    width: 40rpx;
    height: 40rpx;
    margin-bottom: 8rpx;
  }
}

.product-actions {
  padding: $uni-spacing-row-xl;
  background-color: #fff;
  margin-bottom: $uni-spacing-row-base;
}

.attrs,
.specs {
  display: flex;
  flex-direction: column;
}

.attr {
  display: flex;
  margin-bottom: $uni-spacing-row-xl;
}

.spec {
  display: flex;
  margin-bottom: $uni-spacing-row-xl;
}

.attr-name,
.spec-name {
  flex-shrink: 0;
  font-size: $uni-font-size-base;
  font-weight: bold;
  color: $uni-text-color;
  padding: $uni-spacing-row-base 0;
}

.attr-values {
  flex: 1;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.attr-value {
  display: flex;
  align-items: center;
  width: 170rpx;
  background: #fff;
  font-size: $uni-font-size-sm;
  color: $uni-text-color-secondary;
  padding: $uni-spacing-row-base;
  margin-left: $uni-spacing-row-lg;
  margin-bottom: $uni-spacing-row-base;
  border: 1rpx solid $uni-border-color;
  border-radius: $uni-border-radius-lg;

  &.selected {
    background-color: #fff7f8;
    color: $uni-color-primary;
    border-color: #fadde1;
    font-weight: 500;
  }
}

.spec-values {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.spec-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  font-size: $uni-font-size-base;
  color: $uni-text-color-secondary;
  padding: $uni-spacing-row-sm $uni-spacing-row-base;
  margin-left: $uni-spacing-row-lg;
  margin-bottom: $uni-spacing-row-base;
  border: 1rpx solid $uni-border-color;
  border-radius: $uni-border-radius-lg;

  &.selected {
    background-color: #fff7f8;
    color: $uni-color-primary;
    border-color: #fadde1;
  }
}

.spec-actions {
  display: flex;
  align-items: center;
}

.spec-action {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: $uni-spacing-row-lg;
  font-size: $uni-font-size-sm;
  color: $uni-text-color;

  image {
    width: 50rpx;
    height: 50rpx;
  }
}

.spec-count {
  font-size: $uni-font-size-base;
  color: $uni-text-color;
}

.detail {
  position: relative;
  background-color: #fff;
  padding-bottom: 230rpx; /* 改为 padding-bottom 而不是 margin-bottom */
}

.detail-title {
  padding: $uni-spacing-row-xl;
  font-size: $uni-font-size-base;
  color: $uni-text-color;
  border-bottom: 1rpx solid $uni-border-color;
}

.detail-desc {
  padding: $uni-spacing-row-xl;
  font-size: $uni-font-size-sm;
  color: $uni-text-color-grey;
  line-height: 1.5;
  white-space: pre-line;
}

.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  height: 230rpx;
  padding: 0 $uni-spacing-row-lg;

  &-content {
    padding: $uni-spacing-row-lg 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  &-left {
    display: flex;
    flex-direction: column;
  }

  &-right {
    display: flex;
    align-items: center;
    gap: $uni-spacing-row-lg;
    font-size: $uni-font-size-sm;
    color: $uni-text-color;

    image {
      width: 50rpx;
      height: 50rpx;
    }
  }

  &-price {
    font-size: $uni-font-size-lg;
    color: $uni-text-color;
    font-weight: bold;
    margin-bottom: $uni-spacing-row-sm;
  }

  &-attrs {
    font-size: $uni-font-size-sm;
    color: $uni-text-color-grey;
  }

  &-actions {
    display: flex;
    align-items: center;
    gap: $uni-spacing-row-lg;
  }

  &-btn {
    height: 90rpx;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: $uni-font-size-lg;
    color: $uni-text-color;
    font-weight: 400;
    border-radius: $uni-border-radius-xl;
    border: 1rpx solid #dbdbdb;

    &.add {
      background-color: $uni-color-primary;
      color: #fff;
      border: 0;
    }
  }
}
</style>
